<template>
  <div>
    <Modal
      v-model="isShowModal"
      :title="title"
      @on-cancel="hide('formValidate')"
      :mask-closable="false"
      width="950"
    >
      <Form
        ref="formValidate"
        :model="params"
        :rules="ruleValidate"
        label-position="top"
      >
        <FormItem label="模板名称：" prop="freightName">
          <Input
            v-model.trim="params.freightName"
            placeholder="请输入模板名称"
          ></Input>
        </FormItem>
        <FormItem label="默认运费：" prop="firstNum">
          <div>
            <InputNumber
              v-model.trim="params.firstNum"
              :min="1"
              type="number"
              style="width: 70px"
            ></InputNumber>
            件内，
            <InputNumber
              v-model.trim="params.firstPrice"
              type="number"
              :min="0"
              style="width: 70px"
            ></InputNumber>
            元，每增加
            <InputNumber
              v-model.trim="params.nextNum"
              :min="1"
              type="number"
              style="width: 70px"
            ></InputNumber>
            件，增加
            <InputNumber
              v-model.trim="params.nextPrice"
              :min="0"
              type="number"
              style="width: 70px"
            ></InputNumber>
            元
          </div>
          <Alert show-icon style="margin-top: 10px">
            除指定地区外，其余地区运费采用“默认运费”
          </Alert>
        </FormItem>
        <FormItem label="指定地区：" prop="detailList">
          <div
            class="j-freight-detail-row"
            v-for="(item, index) in params.detailList"
            :key="index"
          >
            <Select v-model="item.isDelivery" style="width:100px">
              <Option value="1">可配送</Option>
              <Option value="2">不可配送</Option>
            </Select>
            <Button
              style="margin-left: 5px; margin-right: 5px"
              @click="showSelectRegion(item, index)"
            >
              选择地区（已选{{ item.regionId.length }}个地区）
            </Button>
            <InputNumber
              v-model.trim="item.firstNum"
              :min="1"
              type="number"
              style="width: 70px"
            ></InputNumber>
            件内，
            <InputNumber
              v-model.trim="item.firstPrice"
              :min="0"
              type="number"
              style="width: 70px"
            ></InputNumber>
            元，每增加
            <InputNumber
              v-model.trim="item.nextNum"
              :min="1"
              type="number"
              style="width: 70px"
            ></InputNumber>
            件，增加
            <InputNumber
              v-model.trim="item.nextPrice"
              :min="0"
              type="number"
              style="width: 70px"
            ></InputNumber>
            元
            <Button
              type="error"
              style="margin-left: 13px;"
              @click="removeRegion(index)"
            >
              删除
            </Button>
          </div>
          <Button type="primary" style="margin-top: 10px" @click="addRegion">
            新增地区
          </Button>
        </FormItem>
      </Form>

      <!-- 重写对话框底部按钮 -->
      <div slot="footer">
        <Button @click="hide('formValidate')">取消</Button>
        <Button
          v-if="type != 1"
          type="primary"
          @click="handleSubmit('formValidate')"
          :loading="loadingBtn"
        >
          <span v-if="!loadingBtn">确定</span>
          <span v-else>请稍候...</span>
        </Button>
      </div>
    </Modal>

    <!-- 选择省份 -->
    <Modal
      v-model="isShowRegionModal"
      title="选择省份"
      :mask-closable="false"
      width="900"
      draggable
    >
      <CheckboxGroup v-model="selectRegionValue" @on-change="changeRegion">
        <Checkbox
          style="margin-top: 5px; margin-bottom: 5px"
          :disabled="item.disabled"
          :label="item.regionId"
          border
          v-for="(item, index) in regionList"
          :key="index"
        >
          {{ item.localName }}
        </Checkbox>
      </CheckboxGroup>
    </Modal>
  </div>
</template>

<script>
  export default {
    name: 'freight-ope',
    props: ['regionList'],
    data() {
      return {
        isShowRegionModal: false,
        isShowModal: false,
        loadingBtn: false,
        title: '查看信息',
        selectRegionIndex: 0,
        selectRegionValue: [],
        type: 0,
        params: {
          freightId: '',
          freightName: '',
          firstNum: 1,
          firstPrice: 0,
          nextNum: 1,
          nextPrice: 0,
          detailList: [
            {
              regionId: [],
              isDelivery: '1',
              firstNum: 1,
              firstPrice: 0,
              nextNum: 1,
              nextPrice: 0
            }
          ]
        },
        ruleValidate: {
          freightName: [
            {
              required: true,
              message: '运费模板名称不能为空',
              trigger: 'change'
            }
          ]
        }
      };
    },
    methods: {
      // 点击提交验证
      handleSubmit(name) {
        // console.log(this.params);
        this.$refs[name].validate(valid => {
          if (valid) {
            // this.$Message.error('验证通过');
            /**
             * type判断
             * 1.查看 2.新增 3.编辑
             */
            switch (this.type) {
              case 1:
                // this.title = '查看运费模板';
                break;
              case 2:
                // 新增运费模板
                this.addFreight();
                break;
              case 3:
                // 编辑运费模板
                this.editFreight();
                break;
              default:
                this.$Notice.error({
                  title: '运费模板管理',
                  desc: '查看，新增，编辑区分判断报错',
                  duration: 0
                });
                break;
            }
          } else {
            this.$Message.error('还有信息没有填写合格哦~');
          }
        });
      },
      // 显示模态框
      show(type, row) {
        this.isShowModal = true;
        this.type = type;
        /**
         * type判断
         * 1.查看 2.新增 3.编辑
         */
        switch (type) {
          case 1:
            this.title = '查看运费模板';
            this.queryFreightdetail(row);
            break;
          case 2:
            this.title = '新增运费模板';
            break;
          case 3:
            this.title = '编辑运费模板';
            this.queryFreightdetail(row);
            break;
          default:
            this.$Notice.error({
              title: '运费模板管理',
              desc: '查看，新增，编辑模态框报错',
              duration: 0
            });
            break;
        }
      },
      // 新增运费模板
      addFreight() {
        this.$Spin.show();
        this.axios.post('/freight/addFreight', this.params).then(res => {
          setTimeout(() => {
            this.$Spin.hide();
          }, 300);
          if (res.status == 200) {
            this.$emit('changeDate');
            this.$Message.success('操作成功.');
            this.hide('formValidate');
          }
          if (res.status == 201) {
            this.$Message.error(res.msg);
          }
          if (res.status == 500) {
            this.$Notice.error({
              title: '服务器内部错误',
              desc: '新增运费模板接口报错',
              duration: 0
            });
          }
        });
      },
      // 编辑运费模板
      editFreight() {
        this.$Spin.show();
        this.axios.post('/freight/editFreight', this.params).then(res => {
          setTimeout(() => {
            this.$Spin.hide();
          }, 300);
          if (res.status == 200) {
            this.$emit('changeDate');
            this.$Message.success('操作成功.');
            this.hide('formValidate');
          }
          if (res.status == 201) {
            this.$Message.error(res.msg);
          }
          if (res.status == 500) {
            this.$Notice.error({
              title: '服务器内部错误',
              desc: '编辑运费模板接口报错',
              duration: 0
            });
          }
        });
      },
      // 查询运费模板详情
      queryFreightdetail(row) {
        this.$Spin.show();
        this.axios
          .post('/freight/queryFreightdetail', {
            freightId: row.freightId
          })
          .then(res => {
            setTimeout(() => {
              this.$Spin.hide();
            }, 300);
            if (res.status == 200) {
              // this.$Message.success('操作成功.');
              if (res.data.freight) {
                this.params.freightId = res.data.freight.freightId;
                this.params.freightName = res.data.freight.freightName;
                this.params.firstNum = res.data.freight.firstNum;
                this.params.firstPrice = res.data.freight.firstPrice;
                this.params.nextNum = res.data.freight.nextNum;
                this.params.nextPrice = res.data.freight.nextPrice;
              }
              if (res.data.freightDetail.length) {
                let arr = [];
                res.data.freightDetail.forEach(v => {
                  arr.push({
                    firstNum: v.firstNum,
                    firstPrice: v.firstPrice,
                    nextNum: v.nextNum,
                    nextPrice: v.nextPrice,
                    regionId: JSON.parse(v.regionId),
                    isDelivery: v.isDelivery.toString()
                  });
                });
                this.params.detailList = arr;
              }
            }
            if (res.status == 201) {
              this.$Message.error(res.msg);
            }
            if (res.status == 500) {
              this.$Notice.error({
                title: '服务器内部错误',
                desc: '查看运费模板详情接口报错',
                duration: 0
              });
            }
          });
      },
      // 显示选择地区
      showSelectRegion(item, index) {
        this.isShowRegionModal = true;
        this.selectRegionIndex = index;
        this.regionList.forEach(v => {
          v.disabled = false;
        });
        this.selectRegionValue = [];
        this.returnRegion(index);
      },
      // 选择省份的回显
      returnRegion(index) {
        let arr = [];
        // 回显所有已选择的地区
        this.params.detailList.forEach((v, i) => {
          v.regionId.forEach(y => {
            arr.push({ regionId: y, index: i });
            this.selectRegionValue.push(y);
          });
        });
        // 禁用不是当前行选择的城市
        arr.forEach(v => {
          this.regionList.forEach(y => {
            if (v.regionId == y.regionId) {
              if (v.index != index) {
                y.disabled = true;
                return;
              }
            }
          });
        });
      },
      // 点击地区时
      changeRegion(e) {
        let arr = [];
        e.forEach(v => {
          this.regionList.forEach(y => {
            if (v == y.regionId) {
              if (!y.disabled) {
                arr.push(v);
              }
            }
          });
        });
        this.params.detailList[this.selectRegionIndex].regionId = arr;
      },
      // 新增一条地区数据
      addRegion() {
        this.params.detailList.push({
          regionId: [],
          isDelivery: '1',
          firstNum: 1,
          firstPrice: 0,
          nextNum: 1,
          nextPrice: 0
        });
      },
      // 删除一条地区数据
      removeRegion(index) {
        this.params.detailList.splice(index, 1);
      },
      // 关闭模态框
      hide(name) {
        this.isShowModal = false;
        this.params.freightId = '';
        this.params.firstNum = 1;
        this.params.firstPrice = 0;
        this.params.nextNum = 1;
        this.params.nextPrice = 0;
        this.params.freightName = '';
        this.params.detailList = [
          {
            regionId: [],
            isDelivery: '1',
            firstNum: 1,
            firstPrice: 0,
            nextNum: 1,
            nextPrice: 0
          }
        ];
        this.$refs[name].resetFields();
      }
    }
  };
</script>

<style scoped>
  .j-freight-detail-row {
    margin-top: 10px;
  }

  .j-freight-detail-row:first-of-type {
    margin-top: 0px;
  }
</style>
